<template>
  <div>
    <RePage>
      <MyFormCreate :clear-event="getTableList" v-model="searchFrom" :rule="searchFormRules" :key="key">
        <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
        <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
      </MyFormCreate>
      <div>
        <el-button v-auth="'system.project.create'" type="primary" :icon="Plus" @click="add">添加</el-button>
        <!-- <el-button type="danger" :icon="Delete" :disabled="!selectionData.length" @click="deletes()">批量删除</el-button> -->
      </div>
      <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)" showOverflowTooltip border
        @selection-change="selectionChange" :isShowPag="false">
        <template #action="{ row }">
          <el-space>
            <sj-link custom-type="sblue" :underline="false" @click="edit(row)"
              v-auth="'system.project.update'">编辑</sj-link>
            <sj-link custom-type="sblue" :underline="false" @click="packages(row)"
              v-auth="'system.project-setmeal.create'">套餐</sj-link>
            <sj-link custom-type="sblue" :underline="false" @click="unity(row)"
              v-auth="'system.project.create'">监管授权</sj-link>
            <sj-link custom-type="sred" :underline="false" @click="deletes(row)"
              v-auth="'system.project.remove'">删除</sj-link>
          </el-space>
        </template>
      </pure-table>
      <div class="mt-5">
        <el-pagination v-model:current-page="searchFrom.page" v-model:page-size="searchFrom.limit" background
          :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
      </div>
    </RePage>
  </div>
</template>
<script lang="ts" setup>
import {isNullOrEmpty,initPureTableConfig} from '@/utils/functions'
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";
import editForm from "./form.vue";
import packageInfo from "./components/packages/form.vue";
import unitys from "../components/index.vue";
import { reactive, ref, h } from 'vue';
import { PAGE_LAYOUT } from '@/constant';
import { Plus, } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { addpackageInfo } from '@/api/manage/projectManagementes/packagies/index';
import { getList, getInfo, addInfo, editInfo, deleteInfo } from '@/api/manage/projectManagementes/projectManagementes/index';
import { titles, defaultSearchFrom, prompt, defaultInfoFrom, packagedefaultInfoFrom } from './index';
import { addDialog } from "@/components/ReDialog";
import { deviceDetection, debounce } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customPromiseDebounce } from "@/utils/functions";
import { usePageVariablesStoreHook, } from '@/store/modules/pageVariables'
const operate = usePageVariablesStoreHook().getOperate()  // 操作仓库
const route = useRoute()  // 获取路由参数
const searchFrom = ref(defaultSearchFrom());  // 搜索表单
const key = ref(0); // 刷新表单
const showInfo = ref(); // 弹窗数据
const formRef = ref();
const tableData = reactive({ // 列表数据
  data: [],
  total: 0,
});

const searchFormRules = [
  {
    type: 'input', field: 'unityName', title: '单位名称', value: null, props: {
      placeholder: '请输入单位名称', clearable: true
    }
  },
  {
    type: 'input', field: 'projectName', title: titles.projectName, value: null, props: {
      placeholder: prompt.projectName, clearable: true
    }
  },
  {
    type: 'select', field: 'isWillExpired', title: titles.isWillExpired, value: null, 
    options: [
      { label: '即将到期', value: 1 },
    ],
    props: {
      placeholder: prompt.isWillExpired, clearable: true
    }
  },
  {
    type: 'select', field: 'isSetmealLower', title: titles.isSetmealLower, value: null, 
    options: [
      { label: '短信不足', value: 1 },
      { label: '语音不足', value: 2 },
    ],
    props: {
      placeholder: prompt.isSetmealLower, clearable: true
    }
  },
  { type: 'number', field: 'page', title: 'page', hidden: true },
  { type: 'number', field: 'limit', title: 'limit', hidden: true },
]; // 搜索表单规则
const selectionData = ref([]); // 批量操作选中数据
const roleTableConfig = [
  // { type: "selection", align: "left" },
  { prop: 'id', label: titles.id, width:  100, fixed: 'left' },
  { prop: 'unityName', label: titles.unityName, minWidth: 150 },
  { prop: 'projectName', label: titles.projectName, minWidth: 150 },
  { prop: 'city', label: titles.city, minWidth: 150 },
  { prop: 'expireDate', label: titles.expireDate, minWidth: 100 },
  { prop: 'smsCount', label: titles.smsCount, minWidth: 100 },
  { prop: 'voiceCount', label: titles.voiceCount, minWidth: 100 },
  { slot: 'action', label: titles.action, width: 190, fixed: 'right' },
];  // 表格配置
onMounted(() => {
  if (route.query.unityName) {
    searchFrom.value.unityName = route.query.unityName as string
    key.value++
  }
  if (route.query.isWillExpired) {
    searchFrom.value.isWillExpired =Number(route.query.isWillExpired)
    key.value++
  }
  if (route.query.isSetmealLower) {
    searchFrom.value.isSetmealLower =Number(route.query.isSetmealLower)
    key.value++
  }
  getTableList() // 获取列表数据
});
// 获取列表数据
const getTableList = () => {

  getList(searchFrom.value).then(res => { //获取项目列表数据
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
      // console.log("ss", tableData.data);

    }
  })
}
// 重置搜索栏
const resetting = () => {//点击重置按键
  Object.assign(searchFrom.value, defaultSearchFrom())
  key.value++
  getTableList() // 重置搜索栏后重新请求数据
}

//授权单位
const unity = (row) => {
  addDialog({
    title: `项目监管授权`,
    showClose: true,
    width: "1100px",
    draggable: true,
    props: {
      isLoading: false,
      formInline: row
    },
    fullscreen: deviceDetection(),
    fullscreenIcon: false,
    closeOnClickModal: false,
    contentRenderer: () => h(unitys, { ref: formRef }),
  })
}
// 操作套餐
const packages = (row) => {
  addDialog({
    title: `套餐操作`,
    width: "800px",
    draggable: true, // 是否可拖拽
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false, // 是否可点击遮罩关闭
    contentRenderer: () => h(packageInfo, { ref: formRef }), // 弹框内容
    openAutoFocus({ options, index }) {
      options.props = { // 弹框表单数据
        isLoading: false,
        formInline: packagedefaultInfoFrom()
      }

    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef(); // 获取弹框表单实例
      const formData = options.props.formInline; // 弹框表单数据
      formData.projectId = row.id

      FormRef.validate(valid => { // 弹框表单校验
        if (valid && !options.props?.isLoading) {
          console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;

          addpackageInfo(formData).then(res => {
            if (res.code == 200) {

              message(`操作成功`, {
                type: "success"
              });
              done(); // 关闭弹框
              getTableList(); // 刷新表格数据

            }
            options.props.isLoading = false;
          }).catch((err) => {
            if (err !== '请求中') {
              options.props.isLoading = false;
            }
          })

        }
      });
    }
  });
}
// 新增
const add = (row) => {
  showInfo.value = {}
  openDialog()
}
const selectionChange = data => { //列表多选择
  selectionData.value = data;
};
// 打开编辑弹窗
const edit = (row) => {
  showInfo.value = {}
  openDialog("编辑项目", row)
}
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(
    `确认删除${row ? '当前' : '选中的'}数据?`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteInfo({ ids: row ? [row.id] : selectionData.value.map(item => item.id) }).then(res => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableList();
        }
      })
    })
}
// 开启弹窗
const openDialog = (title = "添加项目", row?: any) => {
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(editForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (row) {
        options.props = {   //打开弹窗携带的参数
          isLoading: true,
          formInline: defaultInfoFrom()
        }
        getInfo({ id: row.id }).then(res => {   //获取项目详情
          if (res.code == 200) {
            showInfo.value = res.result
            options.props.formInline = res.result
            if (res.result.openFunc == null) {
              options.props.formInline.openFunc = []
            }
          }
        }).finally(() => {
          options.props.isLoading = false
        })
      } else {
        options.props = {
          isLoading: false,
          formInline: defaultInfoFrom()
        }
      }
    },
    beforeSure: (done, { options }) => { //点击确认按钮
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "添加项目") {
            DebounceAddInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            DebounceEditInfo(formData).then(res => {    //编辑项目
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }
        }
      });
    }
  });
}

// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
</script>
<style lang="scss" scoped></style>
